package com.unionftech.common.network

import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okio.BufferedSink
import okio.use
import java.io.File
import java.io.FileInputStream

class UploadProgressRequestBody(
    val file: File,
    private val contentType: String,
    val listener: UploadListener
) : RequestBody() {
    companion object {
        private const val DEFAULT_BUFFER_SIZE = 2048
    }

    override fun contentType(): MediaType? = contentType.toMediaTypeOrNull()

    override fun contentLength(): Long = file.length()

    override fun writeTo(sink: BufferedSink) {
        val fileLength = file.length()
        val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
        var uploaded: Long = 0

        FileInputStream(file).use { fis ->
            var read: Int
            while (fis.read(buffer).also { read = it } != -1) {
                listener.onProgressUpdate((100 * uploaded / fileLength).toInt())
                uploaded += read.toLong()
                sink.write(buffer, 0, read)
            }
        }
    }
}